package com.gltc.util;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.File;

import javax.imageio.ImageIO;

public class MyImageUtil {
	/**
     * 图片背景颜色  是否是白亮色 。
     * 该方法是取背景块所有像素点均为要求颜色，可优化为像素点白色比例大于80%，能提高通过概率
     * @param srcImageFile 源图像地址
     * @param width 目标取图宽度
     * @param height 目标取图高度
     */
    public final static boolean isWhiteColor(String srcImageFile,
            int x, int y, int width, int height) {
        try {
            // 读取源图像
            BufferedImage bi = ImageIO.read(new File(srcImageFile));
            int srcWidth = bi.getHeight(); // 源图宽度
            int srcHeight = bi.getWidth(); // 源图高度
            if (srcWidth > 0 && srcHeight > 0) {
                Image image = bi.getScaledInstance(srcWidth, srcHeight,
                        Image.SCALE_DEFAULT);
                // 四个参数分别为图像起点坐标和宽高
                ImageFilter cropFilter = new CropImageFilter(x, y, width, height);
                Image img = Toolkit.getDefaultToolkit().createImage(
                        new FilteredImageSource(image.getSource(),
                                cropFilter));
                BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics g = tag.getGraphics();
                g.drawImage(img, 0, 0, width, height, null); // 绘制切割后的图
                g.dispose();
                
                int[] rgb = new int[3];
                int minx = tag.getMinX();  
                int miny = tag.getMinY(); 
                
                int countPoint = (width-x)*(height-y);
                int sumPoint = 0;
                for (int i = minx; i < width; i++) {  
                    for (int j = miny; j < height; j++) {  
                        int pixel = tag.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字  
                        rgb[0] = (pixel & 0xff0000) >> 16;  
                        rgb[1] = (pixel & 0xff00) >> 8;  
                        rgb[2] = (pixel & 0xff);  
                        /*System.out.println("i=" + i + ",j=" + j + ":(" + rgb[0] + ","  
                                + rgb[1] + "," + rgb[2] + ")");*/
                        if (rgb[0]<235 || rgb[1]<235 || rgb[2]<235 ) {
							sumPoint+=1;
                        	//return false;
						}
                    }  
                }
                if (sumPoint/countPoint > 2/10) {
                	return false;
				}
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    
}
